define([
    'dojo/_base/declare',
    'dojo/_base/array',
    'esri/Color',
    'dojo/_base/connect',
    'esri/SpatialReference',
    'esri/geometry/Point',
    'esri/graphic',
    'esri/symbols/SimpleMarkerSymbol',
    'esri/symbols/TextSymbol',
    'esri/dijit/PopupTemplate',
    'geomap/plugins/layers/ExGraphicsLayer',
    // "esri/layers/GraphicsLayer"
], function (
    declare,
    arrayUtils,
    Color,
    connect,
    SpatialReference,
    Point,
    Graphic,
    SimpleMarkerSymbol,
    TextSymbol,
    PopupTemplate,
    ExGraphicsLayer
) {
    return declare([ExGraphicsLayer], {
        type: 'clusterLayer',
        constructor: function (options) {
            // options:
            //   data:  Object[]
            //     Array of objects. Required. Object are required to have properties named x, y and attributes. The x and y coordinates have to be numbers that represent a points coordinates.
            //   distance:  Number?
            //     Optional. The max number of pixels between points to group points in the same cluster. Default value is 50.
            //   labelColor:  String?
            //     Optional. Hex string or array of rgba values used as the color for cluster labels. Default value is #fff (white).
            //   labelOffset:  String?
            //     Optional. Number of pixels to shift a cluster label vertically. Defaults to -5 to align labels with circle symbols. Does not work in IE.
            //   resolution:  Number
            //     Required. Width of a pixel in map coordinates. Example of how to calculate:
            //     map.extent.getWidth() / map.width
            //   showSingles:  Boolean?
            //     Optional. Whether or graphics should be displayed when a cluster graphic is clicked. Default is true.
            //   singleSymbol:  MarkerSymbol?
            //     Marker Symbol (picture or simple). Optional. Symbol to use for graphics that represent single points. Default is a small gray SimpleMarkerSymbol.
            //   singleTemplate:  PopupTemplate?
            //     PopupTemplate</a>. Optional. Popup template used to format attributes for graphics that represent single points. Default shows all attributes as "attribute = value" (not recommended).
            //   maxSingles:  Number?
            //     Optional. Threshold for whether or not to show graphics for points in a cluster. Default is 1000.
            //   webmap:  Boolean?
            //     Optional. Whether or not the map is from an ArcGIS.com webmap. Default is false.
            //   spatialReference:  SpatialReference?
            //     Optional. Spatial reference for all graphics in the layer. This has to match the spatial reference of the map. Default is 102100. Omit this if the map uses basemaps in web mercator.
        },
        // override esri/layers/GraphicsLayer methods
        _setMap: function (map, surface) {
            this._map = map;
            if (!map) {
                return;
            }
            // calculate and set the initial resolution
            this._clusterResolution = map.extent.getWidth() / map.width; // probably a bad default...

            //this._setAddGraphics()

            // connect to onZoomEnd so data is re-clustered when zoom level changes
            this._zoomEnd = connect.connect(map, 'onZoomEnd', this, function () {
                // update resolution
                this._clusterResolution = map.extent.getWidth() / map.width;
                this.clear();

                this._setClusterGraphicsByScale(map);
            });

            // GraphicsLayer will add its own listener here
            var div = this.inherited(arguments);
            return div;
        },
        _unsetMap: function () {
            this.inherited(arguments);
            connect.disconnect(this._zoomEnd);
        },
        __refresh: function () {
            this._setAddGraphics();
        },
        _setAddGraphics: function () {
            var map = this._map;
            if (!map) {
                return;
            }
            var scale = map.getScale();
            var level = map.getLevel();
            if (!this._clusterData || this._clusterData.length < 1) {
                return;
            }
            var length = this._clusterData.length;

            if (
                this._thresholdValue >= length ||
                scale <= this._clusterUpperLimitScale ||
                (this._clusterUpperLimitLevel && level >= this._clusterUpperLimitLevel)
            ) {
                this._addSingles(this._clusterData);
            } else {
                this._clusterGraphics();
            }
        },
        _setClusterGraphicsByScale: function () {
            var map = this._map;
            if (!map) {
                return;
            }

            var scale = map.getScale();
            if (!this._clusterData || this._clusterData.length < 1) {
                return;
            }
            var length = this._clusterData.length;

            if (this._minScale && this._maxScale) {
                if (scale <= this._minScale && scale >= this._maxScale) {
                    this._setAddGraphics(map);
                }
            } else if (this._minScale) {
                if (scale <= this._minScale) {
                    this._setAddGraphics(map);
                }
            } else if (this._maxScale) {
                if (scale >= this._maxScale) {
                    this._setAddGraphics(map);
                }
            } else {
                this._setAddGraphics(map);
            }
        },
        // public ClusterLayer methods
        add: function (p) {
            if (p.declaredClass) {
                this.inherited(arguments);
                return;
            }

            // add the new data to _clusterData so that it's included in clusters
            // when the map level changes
            this._clusterData.push(p);
            var clustered = false;
            // look for an existing cluster for the new point
            for (var i = 0; i < this._clusters.length; i++) {
                var c = this._clusters[i];
                if (this._clusterTest(p, c)) {
                    // add the point to an existing cluster
                    this._clusterAddPoint(p, c);
                    // update the cluster's geometry
                    this._updateClusterGeometry(c);
                    // update the label
                    this._updateLabel(c);
                    clustered = true;
                    break;
                }
            }

            if (!clustered) {
                this._clusterCreate(p);
                p.attributes.clusterCount = 1;
                this._showCluster(p);
            }
        },
        clear: function () {
            // Summary:  Remove all clusters and data points.
            this.inherited(arguments);
            if (this._clusters && this._clusters.length > 0) {
                this._clusters.length = 0;
            }
        },
        clearSingles: function (singles) {
            // Summary:  Remove graphics that represent individual data points.
            var s = singles || this._singles;
            arrayUtils.forEach(
                s,
                function (g) {
                    this.remove(g);
                },
                this
            );
            this._singles.length = 0;
        },
        getGraphicLocation: function (mapView, e) {
            var geometry = e.graphic.geometry;
            var lngFieldName = this.lngFieldName;
            var latFieldName = this.latFieldName;
            var location = {};
            location[lngFieldName] = geometry.x;
            location[latFieldName] = geometry.y;
            location.x = geometry.x;
            location.y = geometry.y;
            return location;
        },
        onClick: function (e) {
            this._removeLastSingles();
            var _this = this;
            var evt = { _esriEvent: e, mapUtils: _this.mapUtils };
            evt.data = e.graphic.attributes;
            evt.getLocation = function () {
                return _this.getGraphicLocation(_this.mapUtils, e);
            };
            var attr = e.graphic.attributes;
            _this._map.infoWindow.hide();
            _this.mapUtils._currentClickLayer = _this.options.layerName;
            var scale = this._map.getScale();
            var level = this._map.getLevel();
            var length = this._clusterData.length;

            if (
                this._thresholdValue >= length ||
                scale <= this._clusterUpperLimitScale ||
                (this._clusterUpperLimitLevel && level >= this._clusterUpperLimitLevel)
            ) {
                //散开
                if (e.stopPropagation) {
                    e.stopPropagation();
                }

                if (typeof this._clickEvent == 'function') {
                    this._clickEvent(evt);
                }
            } else {
                // remove any previously showing single features
                // this.clearSingles(this._singles);

                // find single graphics that make up the cluster that was clicked
                // would be nice to use filter but performance tanks with large arrays in IE

                var singles = [];

                for (var i = 0, il = this._clusterData.length; i < il; i++) {
                    var entity = this._clusterData[i];
                    if (attr.clusterId == entity.attributes.clusterId) {
                        singles.push(entity);
                        if (attr.clusterCount == 1) {
                            Object.assign(attr, entity);
                            break;
                        }
                    }
                }
                this._showAllClusterPt();
                if (singles.length > this._maxSingles) {
                    //console.log("Sorry, that cluster contains more than " + this._maxSingles + " points. Zoom in for more detail.");
                    return;
                } else {
                    if (typeof e.stopPropagation == 'function') {
                        e.stopPropagation();
                    }

                    if (attr.clusterCount == 1) {
                        if (typeof this._clickEvent == 'function') {
                            this._clickEvent(evt);
                        }
                        return;
                    }
                    if (!attr.clusterCount) {
                        if (typeof this._clickEvent == 'function') {
                            this._clickEvent(evt);
                        }
                    }

                    this._hideCurrentClickClusterPt(e.graphic.attributes);
                    // this._addSingles(singles);
                    this._addSingles(singles, (this._currentSingles = []));
                }
            }
        },
        _removeLastSingles: function () {
            var me = this;
            if (!this._currentSingles || this._currentSingles.length < 1) {
                return;
            }
            this._currentSingles.map(function (graphic) {
                me.remove(graphic);
            });
        },
        onMouseOver: function (e) {
            var attr = e.graphic.attributes;
            if (attr.attributes && attr.attributes.clusterCount == 1) {
                var _this = this;
                var evt = { _esriEvent: e, mapView: _this._mapView };
                evt.data = e.graphic.attributes;
                evt.getLocation = function () {
                    return _this.getGraphicLocation(_this.mapView, e);
                };

                //  this._map.infoWindow.hide();
                e.stopPropagation();
                if (typeof this._mouseOverEvent == 'function') {
                    this._mouseOverEvent(evt);
                }
            }
        },
        onMouseOut: function (e) {
            if (typeof this._mouseOutEvent == 'function') {
                var _this = this;
                var evt = { _esriEvent: e, mapView: _this._mapView };
                evt.data = e.graphic.attributes;
                evt.getLocation = function () {
                    return _this.getGraphicLocation(_this.mapView, e);
                };
                this._mouseOutEvent(evt);
            }
        },
        _showAllClusterPt: function () {
            var _this = this;
            var _graphics = _this.graphics;

            _graphics.map(function (item) {
                if (!item.visible) {
                    item.visible = true;
                }
            });
            _this.refresh();
        },
        _hideCurrentClickClusterPt: function (attr) {
            var _this = this;
            var _graphics = _this.graphics;

            _graphics.map(function (item) {
                if (
                    attr.clusterId &&
                    item.attributes.clusterCount != 1 &&
                    item.attributes.clusterId == attr.clusterId
                ) {
                    item.visible = false;
                }
            });
            _this.refresh();
        },
        // internal methods
        _clusterGraphics: function () {
            var length = this._clusterData.length;

            // first time through, loop through the points
            for (var j = 0, jl = length; j < jl; j++) {
                // see if the current feature should be added to a cluster
                var point = this._clusterData[j];
                var clustered = false;
                var numClusters = this._clusters.length;
                for (var i = 0; i < this._clusters.length; i++) {
                    var c = this._clusters[i];
                    if (this._clusterTest(point, c)) {
                        this._clusterAddPoint(point, c);
                        clustered = true;
                        break;
                    }
                }

                if (!clustered) {
                    this._clusterCreate(point);
                }
            }
            this._showAllClusters();
        },
        _clusterTest: function (p, cluster) {
            var distance =
                Math.sqrt(Math.pow(cluster.x - p.x, 2) + Math.pow(cluster.y - p.y, 2)) /
                this._clusterResolution;
            return distance <= this._clusterTolerance;
        },
        // points passed to clusterAddPoint should be included
        // in an existing cluster
        // also give the point an attribute called clusterId
        // that corresponds to its cluster
        _clusterAddPoint: function (p, cluster) {
            // average in the new point to the cluster geometry
            var count, x, y;
            // p.x = p[this.lngFieldName];
            // p.y = p[this.latFieldName];
            count = cluster.attributes.clusterCount;
            x = (p.x + cluster.x * count) / (count + 1);
            y = (p.y + cluster.y * count) / (count + 1);
            cluster.x = x;
            cluster.y = y;

            // build an extent that includes all points in a cluster
            // extents are for debug/testing only...not used by the layer
            if (p.x < cluster.attributes.extent[0]) {
                cluster.attributes.extent[0] = p.x;
            } else if (p.x > cluster.attributes.extent[2]) {
                cluster.attributes.extent[2] = p.x;
            }
            if (p.y < cluster.attributes.extent[1]) {
                cluster.attributes.extent[1] = p.y;
            } else if (p.y > cluster.attributes.extent[3]) {
                cluster.attributes.extent[3] = p.y;
            }

            // increment the count
            cluster.attributes.clusterCount++;
            // attributes might not exist
            if (!p.hasOwnProperty('attributes')) {
                p.attributes = {};
            }
            // give the graphic a cluster id
            p.attributes.clusterId = cluster.attributes.clusterId;
        },

        // point passed to clusterCreate isn't within the
        // clustering distance specified for the layer so
        // create a new cluster for it
        _clusterCreate: function (p) {
            var clusterId = this._clusters.length + 1;

            if (!p.attributes) {
                p.attributes = {};
            }
            p.attributes.clusterId = clusterId;

            // var cluster = Object.assign({}, p);

            // cluster.attributes.clusterCount = 1;
            // cluster.attributes.extent = [p.x, p.y, p.x, p.y];

            var cluster = {
                ...p,
                // "x": p.x,
                // "y": p.y,
                // "symbol": p.symbol,
                attributes: {
                    ...p,
                    x: p._x,
                    y: p._y,
                    clusterCount: 1,
                    clusterId: clusterId,
                    extent: [p.x, p.y, p.x, p.y],
                },
            };

            this._clusters.push(cluster);
        },

        _showAllClusters: function () {
            // for (let i = 0, il = this._clusters.length; i < il; i++) {
            //     var c = this._clusters[i];
            //     if (c.attributes.clusterCount > 1) {
            //         this._showCluster(c);
            //     } else {
            //         this._addSingles([c]);
            //     }
            // }
            for (var i = 0, il = this._clusters.length; i < il; i++) {
                var c = this._clusters[i];
                this._showCluster(c);
            }
        },
        _getClusterSymbol: function (attributes) {
            var clusterCount = attributes.clusterCount;
            if (!this._clusterSymList || this._clusterSymList.length < 1) {
                return;
            }
            var item = null;

            for (var i = 0; i < this._clusterSymList.length; i++) {
                item = this._clusterSymList[i];
                if (clusterCount >= item.begin && clusterCount < item.end) {
                    return item.symbol;
                }
            }
        },
        _showCluster: function (c) {
            var point = new Point(c.x, c.y, this._map.spatialReference);
            var clusterSymbol = this._getClusterSymbol(c.attributes);

            if (c.attributes.clusterCount == 1) {
                // this._addSingles([c]);
                var symbolFieldName = this.options.symbolFieldName || 'symbol';
                this.__getSymbol(this._mapView, c[symbolFieldName], symbol => {
                    this.add(new Graphic(point, symbol || clusterSymbol, c));
                });
                return;
            }

            this.add(new Graphic(point, clusterSymbol, c.attributes));

            // show number of points in the cluster
            var font = new esri.symbol.Font().setSize(10).setWeight(esri.symbol.Font.WEIGHT_BOLD);
            var label = new TextSymbol(c.attributes.clusterCount)
                .setColor(new Color(this._clusterLabelColor))
                .setOffset(0, this._clusterLabelOffset)
                .setFont(font);

            this.add(new Graphic(point, label, c.attributes));
        },

        _addSingles: function (singles, currentClickSingles) {
            var me = this;
            var symbolFieldName = this.options.symbolFieldName || 'symbol';
            arrayUtils.forEach(
                singles,
                function (p) {
                    var symbol = null;
                    if (typeof this._renderSingleCallback == 'function') {
                        symbol = this._renderSingleCallback(p);
                    }

                    if (p[symbolFieldName]) {
                        me.__getSymbol(me._mapView, p[symbolFieldName], function (symbol) {
                            addGraphic(symbol);
                        });
                    } else {
                        symbol = me._singleSym;

                        addGraphic(symbol);
                    }

                    function addGraphic(symbol) {
                        if (!p.attributes) {
                            p.attributes = Object.assign({}, p);
                        }
                        p.attributes.clusterCount = 1;
                        p.clusterId = p.attributes.clusterId;
                        var g = new Graphic(
                            new Point(p.x, p.y, me._map.spatialReference),
                            symbol,
                            p
                            //  me._singleTemplate
                        );
                        if (!currentClickSingles) {
                            me._singles.push(g);
                        } else {
                            currentClickSingles.push(g);
                        }

                        if (me._showSingles) {
                            me.add(g);
                            // if (Object.prototype.toString.call(currentClickSingles) == '[object Array]') {
                            //     currentClickSingles.push(g);
                            // };
                        }
                    }
                },
                me
            );
        },

        _updateClusterGeometry: function (c) {
            // find the cluster graphic
            var cg = arrayUtils.filter(this.graphics, function (g) {
                return !g.symbol && g.attributes.clusterId == c.attributes.clusterId;
            });
            if (cg.length == 1) {
                cg[0].geometry.update(c.x, c.y);
            } else {
                console.log("didn't find exactly one cluster geometry to update: ", cg);
            }
        },

        _updateLabel: function (c) {
            // find the existing label
            var label = arrayUtils.filter(this.graphics, function (g) {
                return (
                    g.symbol &&
                    g.symbol.declaredClass == 'esri.symbol.TextSymbol' &&
                    g.attributes.clusterId == c.attributes.clusterId
                );
            });
            if (label.length == 1) {
                // console.log("update label...found: ", label);
                this.remove(label[0]);
                var newLabel = new TextSymbol(c.attributes.clusterCount)
                    .setColor(new Color(this._clusterLabelColor))
                    .setOffset(0, this._clusterLabelOffset);
                this.add(new Graphic(new Point(c.x, c.y, this._sr), newLabel, c.attributes));
                // console.log("updated the label");
            } else {
                console.log("didn't find exactly one label: ", label);
            }
        },

        // debug only...never called by the layer
        _clusterMeta: function () {
            // print total number of features
            console.log('Total:  ', this._clusterData.length);

            // add up counts and print it
            var count = 0;
            arrayUtils.forEach(this._clusters, function (c) {
                count += c.attributes.clusterCount;
            });
            console.log('In clusters:  ', count);
        },
    });
});
